package com.dpwgc.easywebpay.module.alipay.controller;

import com.alipay.api.AlipayApiException;
import com.dpwgc.easywebpay.base.dao.Order;
import com.dpwgc.easywebpay.base.util.DateUtil;
import com.dpwgc.easywebpay.base.util.ResultUtil;
import com.dpwgc.easywebpay.module.alipay.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

/**
 * 支付宝pc网页支付
 */
@RestController
@RequestMapping("/ali/order")
public class OrderController {

    @Autowired
    OrderService orderService;
    @Autowired
    DateUtil dateUtil;

    /**
     * 用户下单
     * @param itemId 商品id
     * @param userId 用户id
     * @param subject 订单主题
     * @param price 商品价格
     * @return ResultUtil<Order>
     */
    @PostMapping("/buy")
    public ResultUtil<Order> buy(@RequestParam("itemId") long itemId,
                                 @RequestParam("userId") long userId,
                                 @RequestParam("subject") String subject,
                                 @RequestParam("price") double price) throws AlipayApiException {

        Order order = new Order();
        order.setItemId(itemId);
        order.setUserId(userId);
        order.setOrderNo(UUID.randomUUID().toString().replaceAll("-","")); //随机生成订单号
        order.setSubject(subject);
        order.setPrice(price);
        order.setStartTime(dateUtil.getDateTime());
        order.setUpdateTime(dateUtil.getDateTime());
        order.setStatus(0);

        return orderService.buy(order);
    }

    /**
     * 获取支付页面（GET请求，浏览器访问，直接返回html页面，访问链接：http://127.0.0.1:8100/ali/order/getPayPage/html?orderId=1）
     * @param orderId 订单id
     * @return String
     */
    @ResponseBody
    @GetMapping(value = "/getPayPage/html",produces = "text/html")
    public String getPayPage(@RequestParam("orderId") long orderId) {
        return orderService.getPayPage(orderId);
    }

    /**
     * 根据用户id获取用户订单列表（同时检查订单状态）
     * @param userId 用户id
     * @return
     */
    @PostMapping("/list")
    public ResultUtil<Object> list(@RequestParam("userId") long userId) {

        return orderService.list(userId);
    }
}
